<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use frontend\models\Page;
use frontend\models\SeoRedirect;
use yii\web\HttpException;
use frontend\components\InlineWidgetsBehavior;

/**
 * Site controller
 */
class PageController extends Controller
{
    
    public function behaviors()
    {
        return [
            'InlineWidgetsBehavior' => [
                'class'=> InlineWidgetsBehavior::className(),
                'namespace'=> 'frontend\widgets', // default namespace (optional)               
                'widgets'=> \Yii::$app->params['runtimeWidgets'],
                'startBlock'=> '[*',
                'endBlock'=> '*]',
             ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex($alias = 'main')
    {
        //$mainMenuList = Page::getMainMenu();
        $aliasArr = explode('/', $alias);
        $pageData = Page::find()
                    ->with('redirect')
                    ->where(['alias' => end($aliasArr)])
                    ->andWhere(['is_draft' => Page::PUBLISHED])
                    ->andWhere(['id_site' => Yii::$app->params['siteId']])
                    ->one();
        
        if($pageData) 
        {
            if($pageData->redirect)
            {
                $currentNode = Page::findOne(['id' => (int)$pageData->redirect[0]->child_id]);
                //получить полный alias страницы редиректа
                $allParentsNode = $currentNode->getParents()
                                    ->select('id, alias, title')
                                    ->asArray()
                                    ->all();
                return Yii::$app->response->redirect([\frontend\helpers\FriendlyURLHelper::generateURL($allParentsNode, $currentNode->alias)]);
            }

            if($alias != 'main') 
            {
                $this->layout = 'common';
            }

            \Yii::$app->view->registerMetaTag([
                'name' => 'description',
                'content' => $pageData->description,
            ]);

            return $this->render($pageData->view, [
                    //'mainMenuList'=>$mainMenuList, 
                    'pageData'=>$pageData
            ]);
        }
        else 
        {
            throw new HttpException(404, 'Запрашиваемой страницы не существует');
        }   
        return $this->render('index');
    }

    public function actionError()
    {
        $this->layout = 'common';
        $exception = Yii::$app->errorHandler->exception;

        if ($exception !== null) {

            $statusCode = $exception->statusCode;
            $name = $exception->getName();
            $message = $exception->getMessage();

            if($statusCode == '404')
            {
                return $this->render('error404', [
                    'statusCode' => $statusCode,
                ]);
            }
            else
            {
                return $this->render('error', [
                    'statusCode' => $statusCode,
                    'name' => $name,
                    'message' => $message,
                ]);
            }

        }
    }

    public function actionSitemap()
    {
        $newsCollection = \frontend\models\News::find()->select(['id'])->asArray()->all();
        $eventCollection = \frontend\models\Event::find()->select(['id'])->asArray()->all();

        $pageCollection = Page::find()
            ->select(['id', 'alias', 'path', 'is_draft', 'is_hidden'])
            ->where(['id_site' => Yii::$app->params['siteId']])
            ->indexBy('id')
            ->asArray()
            ->all();
            
        $pageCollection = \frontend\helpers\SitemapHelper::rebuildPagePath($pageCollection);

        \Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
        $headers = \Yii::$app->response->headers;
        $headers->add('Content-Type', 'text/xml');

        return $this->renderPartial('sitemap', [
            'newsCollection' => $newsCollection,
            'eventCollection' => $eventCollection,
            'pageCollection' => $pageCollection,
        ]);
    }

}
